<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .content{
            width: 1000px;
            margin: 10px auto;
            height: 500px;
            border: 3px solid red;
            overflow: auto;
        }
        .footer{
            width: 1000px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
   <div class="content">
    
   </div>
   <div class="footer">
        <input type="text" placeholder="请输入姓名" id="name">
        <input type="text" placeholder="请输入内容" id="content"> <button onclick="
        sendMessage()">发送</button>
   </div>
</body>
<script>
    // 创建webSoket实例  soket 协议 (长链接)
    let ws = new WebSocket('ws://127.0.0.1:9002');
    console.log(ws)
    // 监听是否连接成功
    ws.onopen= ()=>{
        console.log("连接成功")
    }

    function sendMessage(){
        let name = document.getElementById("name").value;
        let content = document.getElementById("content").value;
        // 发送消息
        ws.send(JSON.stringify({name,content}))
    }
    // 监听服务端推送的消息
    ws.addEventListener("message",(data)=>{
        console.log(data.data)
        let msg = JSON.parse(data.data);
        let div = document.createElement("div");
        div.innerText = `${msg.name}:${msg.content}`;
        document.querySelector(".content").append(div)
    })
</script>
</html>